#include "Common.h"
#include "Win32Input.h"

namespace GenBen {

Win32Input::Win32Input()
{
	ZeroMemory(&keyboard[0], sizeof(keyboard));
	ZeroMemory(&keyboard_current[0], sizeof(keyboard_current));
	ZeroMemory(&keyboard_last[0], sizeof(keyboard_last));
	ZeroMemory(&mouse[0], sizeof(mouse));
	ZeroMemory(&mouse_current[0], sizeof(mouse_current));
	ZeroMemory(&mouse_last[0], sizeof(mouse_last));

	mouse_pos = mouse_pos_old = VectorI(0, 0);
}

Win32Input::~Win32Input()
{
}

bool Win32Input::isKeyPressed(Key key)
{
	return keyboard[key];
}

bool Win32Input::isKeyUp(Key key)
{
	return (keyboard_last[key] && !keyboard[key]);
}

bool Win32Input::isKeyDown(Key key)
{
	return (!keyboard_last[key] && keyboard[key]);
}

VectorI Win32Input::getMousePos()
{
	return mouse_pos;
}

VectorI Win32Input::getMouseRelativePos()
{
	return VectorI(mouse_pos.x - mouse_pos_old.x, mouse_pos.y - mouse_pos_old.y);
}

int Win32Input::getRelativeWheel()
{
	// TODO
	return 0;
}

bool Win32Input::isMouseButtonPressed(MouseButton button)
{
	return mouse[button];
}

bool Win32Input::isMouseButtonUp(MouseButton button)
{
	return (mouse_last[button] && !mouse[button]);
}

bool Win32Input::isMouseButtonDown(MouseButton button)
{
	return (!mouse_last[button] && mouse[button]);
}

bool Win32Input::process(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	uint16 x, y;

	switch(message)
	{
	case WM_KEYDOWN:
		keyboard_current[wParam & 0xFF] = true;
		break;
	case WM_KEYUP:
		keyboard_current[wParam & 0xFF] = false;
		break;

	case WM_MOUSEMOVE:
		x = (uint16)(lParam & 0xFFFF);
		y = (uint16)(lParam >> 16);
		mouse_pos.x = (int)x;
		mouse_pos.y = (int)y;
		break;

	case WM_LBUTTONDOWN:
		mouse_current[0] = true;
		break;
	case WM_RBUTTONDOWN:
		mouse_current[1] = true;
		break;
	case WM_MBUTTONDOWN:
		mouse_current[2] = true;
		break;

	case WM_LBUTTONUP:
		mouse_current[0] = false;
		break;
	case WM_RBUTTONUP:
		mouse_current[1] = false;
		break;
	case WM_MBUTTONUP:
		mouse_current[2] = false;
		break;

	default:
		return false;
	}
	return true;
}

void Win32Input::update()
{
	memcpy(mouse_last, mouse, sizeof(mouse));
	memcpy(mouse, mouse_current, sizeof(mouse));

	memcpy(keyboard_last, keyboard, sizeof(keyboard));
	memcpy(keyboard, keyboard_current, sizeof(keyboard));

	mouse_pos_old = mouse_pos;
}

}